package com.xshbbs.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xshbbs.entity.Block;
import com.xshbbs.entity.User;
import com.xshbbs.service.BlockService;

@Controller
public class BlockController {
	
	@Autowired
	private BlockService blockService;
	
	@RequestMapping("insertBlock") 
	public String insertBlock(Block block, HttpServletRequest request) {
		
		//只有总版主能添加版块，对应数据库role字段，值为2
		User user = (User) request.getSession().getAttribute("user");
		if(user.getRole() != 2) {
			request.setAttribute("msg", "你没有权限");
			return "forum";
		}
		//添加版块验证，不允许版块名为空
		String admit = this.blockService.admit(block);
		if(!admit.equals("1")) {
			request.setAttribute("msg", admit);
			return "forum";
		}
		
		boolean result = this.blockService.insertBlock(block);
		if(result) {
			return "redirect:forum";
		}
		request.setAttribute("msg", "版块添加失败");
		return "forum";
		
	}
	
	@RequestMapping("deleteBlock")
	public String deleteBlock(int id, HttpServletRequest request) {
		
		User user = (User) request.getSession().getAttribute("user");
		if(user.getRole() != 2) {
			request.setAttribute("msg", "你没有权限");
			return "forum";
		}
		
		boolean result = this.blockService.deleteBlockById(id);
		if(result) {
			return "redirect:forum";
		}
		request.setAttribute("msg", "删除版块失败");
		return "forum";
		
	}
	
	@RequestMapping("updateBlock")
	public String updateBlock(Block block, HttpServletRequest request) {
		
		User user = (User) request.getSession().getAttribute("user");
		if(user.getRole() != 2) {
			request.setAttribute("msg", "你没有权限");
			return "forum";
		}
		
		String admit = this.blockService.admit(block);
		if(!admit.equals("1")) {
			request.setAttribute("msg", admit);
			return "forum";
		}
		
		boolean result = this.blockService.updateBlockById(block);
		if(result) {
			return "redirect:forum";
		}
		request.setAttribute("msg", "删除版块失败");
		return "forum";
		
	}
	
}
